package Server.ServerMainFrame.ServerMainFrameModel.ServerThread;

import Packet.*;
import java.util.*;
import java.io.*;
import Server.ServerMainFrame.ServerMainFrameModel.ServerThread.*;

import Core.Model.*;

import javax.swing.*;

public class DealClientLoginPacket 
{
    public DealClientLoginPacket(Packet packet, Thread thread)
    {
    	this.thread = thread;
    	Properties prop = (Properties)packet.getContent();
    	userName = new String(prop.getProperty(PacketFactory.CLIENT_USER_NAME));
    	password = new String(prop.getProperty(PacketFactory.CLIENT_USER_PASSWORD));
        type = (ClientType)prop.get(PacketFactory.CLIENT_USER_TYPE);
    	login(userName, password, type);
    	
    	System.out.println("here");
    	
    	JOptionPane.showConfirmDialog(null, "message");
    }
    
    public void login(String userName, String password, ClientType type)
    {
    	int i;
    	
    	if (userName == null)
    	{
    		Packet packet = new PacketFactory().makeClientLoginNoAccountPacket(PacketFactory.sourceId, 
        			PacketFactory.destinationId, new String());
        	new SendPacket(packet, this.thread);
    	}
    	if (password == null)
    	{
    		Packet packet = new PacketFactory().makeClientLoginPasswordErrorPacket(PacketFactory.sourceId, 
        			PacketFactory.destinationId, new String());
        	new SendPacket(packet, this.thread);
    	}
    	
    	System.out.println("number : " + this.thread.getModel().ClientNumber);
    	
    	for (i=1; i<=thread.getModel().ClientNumber; i++)
    	{
    		System.out.println(thread.getModel().clientUser[i].getType());
    	}
    	System.out.println("type : " + type);
    	
        for (i=1; i<=thread.getModel().ClientNumber; i++)
        {
        	if (thread.getModel().clientUser[i].getType().equals(type)
        		&& thread.getModel().clientUser[i].getUserName().equals(userName))
        		break;
        }
        
        
        if (i > thread.getModel().ClientNumber)
        {
        	Packet packet = new PacketFactory().makeClientLoginNoAccountPacket(PacketFactory.sourceId, 
        			PacketFactory.destinationId, new String());
        	new SendPacket(packet, this.thread);
        }
        else if (!thread.getModel().clientUser[i].getPassword().equals(password))
        {
        	Packet packet = new PacketFactory().makeClientLoginPasswordErrorPacket(PacketFactory.sourceId, 
        			PacketFactory.destinationId, new String());
        	new SendPacket(packet, this.thread);
        }
        else 
        {
        	Packet packet = new PacketFactory().makeClientLoginSucessfulPacket(PacketFactory.sourceId, 
        			PacketFactory.destinationId, new String());
        	new SendPacket(packet, this.thread);
        }
    }
    
    private String userName;
    private String password;
    private ClientType type;
    private Thread thread;
}
